package com.atkinsglobal.basic.validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class ModelValidator implements Validator {

	private Validator jazuValidator;
	
	public ModelValidator(Validator jazuValidator){
		
		if (jazuValidator == null) {
            throw new IllegalArgumentException(
              "The supplied [Validator] is required and must not be null.");
        }
        if (!jazuValidator.supports(ModelComponent.class)) {
            throw new IllegalArgumentException(
              "The supplied [Validator] must support the validation of [ModelComponent] instances.");
        }

		
		this.jazuValidator = jazuValidator;
	}
	
	@Override
	public boolean supports(Class<?> arg0) {
		
		// can also use isAssignableFrom to also validate subclasses
		return Model.class.equals(arg0);
	}

	@Override
	public void validate(Object obj, Errors err) {
		ValidationUtils.rejectIfEmpty(err, "name", "name.empty");
		Model m = (Model) obj;

		if(m.id<0){
			err.rejectValue("id", "negative");
		}
		
		// Pass component field to jazu validator, which validates components
		try{
			err.pushNestedPath("component");
			ValidationUtils.invokeValidator(this.jazuValidator, m.component, err);
		} finally {
			err.popNestedPath();
		}
		
	}

}
